from django.shortcuts import render,redirect
from markdown import markdown

from .models import MarkdownPage
from .forms import MarkdownPageFrom


def markdown_editor(request, page_id=None):
    if page_id is not None:
        page = MarkdownPage.objects.get(id=page_id)
    else:
        page = MarkdownPage()


    if request.method == 'POST':
        form = MarkdownPageFrom(request.POST, instance=page)
        if form.is_valid():
            form.save()
            return redirect('markdown_view', page_id=page.id)
    else:
        form = MarkdownPageFrom(instance=page)

    return render(request, 'markdown_editor.html', {'form': form})


def markdown_view(request, page_id):
    page = MarkdownPage.objects.get(id=page_id)
    content_html = markdown(page.content)
    return render(request, 'markdown_view.html', {'page': page, 'content_html': content_html})